from sklearn import preprocessing
import os
import pandas as pd


"""
新的表结果：
1.user_list
2.frequent
3.rencent
4.money
5. 
"""

"""
购买商品表1的字段：
 user_id:用户注册ID ;
 auction_id:订单号ID ；
 cat_id:商品具体ID，是在选择“选择单品”时产生 ；
 cat1:商品种类ID，是在“选择商品类别”时产生 ；
 property:商品属性，它是文本型数据，是在“选择尺寸和颜色”时产生 ；
 buy_mount:购买数量 ；day:购买时间
"""

os.chdir(r'C:/Users/wx-5421/Downloads/')
online_data = pd.read_csv("baby_trade1.csv",encoding="ISO-8859-1")
online_data = online_data[['user_id','buy_mount','day']][:300]

print(online_data.buy_mount.describe())
online_data['day'] = pd.to_datetime(online_data.day.astype('str'))
sum_mount = online_data.groupby('user_id').agg({'buy_mount':'sum'})
print("sum_mount: ",sum_mount)

# open_day='2014-07-01'
# close_day='2014-07-30'
# con1=online_data['day']>=open_day
# con2=online_data['day']<close_day
# data1 = online_data[con1&con2]
# data2 = data1.groupby('user_id')
# aa = data1.groupby('user_id').count()['day']
# # print(aa)
# id_count = data1.groupby('user_id').agg({'user_id':'count'})
# # data1['frquent'] = id_count
# print(id_count.size)




"""
R值计算 每个用户最后一次购买时间距今多少天
"""
r = online_data.groupby('user_id')['day'].max().reset_index()
r['R'] = (pd.to_datetime('2014-08-01') - r['day']).dt.days
r = r[['user_id','R']]


"""
F 
"""
#引入日期标签辅助列
online_data['day_f'] = online_data['day'].astype(str).str[:10]
dup_f = online_data.groupby(['user_id'])['day'].count().reset_index()
# f = dup_f.groupby(['user_id','day']).count().reset_index()
# f.colums = ['user_id','F']
# f['user_id']= dup_f['user_id']
# f['F'] =

rm = pd.merge(r,sum_mount,left_on='user_id',right_on='user_id',how='inner')
rfm = pd.merge(rm,dup_f,left_on='user_id',right_on='user_id',how='inner')
print(rfm)
"""
分值计算
1.vip用户 F：大于平均值  R：小于平均值  M：一个月内累计消费大于200
2.低频高消费用户 F：小于平均值  R：大于平均值  M：一个月内累计消费小于200，大于100
3.高频低消费用户 F：大于平均值  R：小于平均值  M：一个月内累计消费小于200，大于100
4.潜力用户 F：小于平均值  R：大于平均值  M：一个月内累计消费小于100
"""

#R-Score值计算
rfm['R-Score'] = pd.cut(rfm['R'],bins=[0,7,15,30,60,100000],labels=[5,4,3,2,1],right=False).astype(float)
#F-Score值计算
rfm['F-Score'] = pd.cut(rfm['day'],bins=[1,3,5,7,9,100000],labels=[1,2,3,4,5],right=False).astype(float)
#M-Score值计算
rfm['M-Score'] = pd.cut(rfm['buy_mount'],bins=[1,50,100,150,200,100000],labels=[1,2,3,4,5],right=False).astype(float)
print(rfm)

rfm['R是否大于平均值'] = (rfm['R-Score'] > rfm['R-Score'].mean())*1
rfm['F是否大于平均值'] = (rfm['F-Score'] > rfm['F-Score'].mean())*1
rfm['M是否大于平均值'] = (rfm['M-Score'] > rfm['M-Score'].mean())*1

rfm['customer_value'] = (rfm['R是否大于平均值']*100) + (rfm['F是否大于平均值']*10) + (rfm['M是否大于平均值']*1)

def transform_label(x):
    if x == 111:
        label = 'vip客户'
    elif x == 110:
        label = '高频低消费用户'
    elif x == 101:
        label = '低频高消费用户'
    elif x == 100:
        label = '新客户'
    else:
        label = '低频低消费用户'
    return label

rfm['customer_tags'] = rfm['customer_value'].apply(transform_label)
print(rfm)


#查看各类用户占比
#创建一个空dataframe
# count = pd.DataFrame(columns=('客户类型','人数','人数占比'))
count = rfm['customer_tags'].value_counts().reset_index()
count.columns = ['客户类型','人数']
count['人数占比'] = count['人数']/count['人数'].sum()
print(count)

#分析不太类型客户消费金额占比
money = rfm.groupby('customer_tags')['buy_mount'].sum().reset_index()
money.columns = ['客户类型','消费金额']
money['金额占比'] = money['消费金额']/money['消费金额'].sum()
print(money)
